<?php

namespace App\Models\Member;

use App\Models\Communicationlog;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class MemberContactLog extends Model
{
    protected $table='member_contact_log';

    //沟通记录列表
    public function getMemberContactList($id){
        $res = DB::table($this->table.' as mcl')
            ->select('mcl.*','au.name as admin_name')
            ->leftJoin('admin_users as au','mcl.admin_user_id','=','au.id')
            ->where('member_id',$id)
            ->where("mcl.mall_id", request()->mallData["id"])
            ->get();
        $res = json_decode(json_encode($res),true);
        //查询客户仓库的沟通记录
        $contact_log = DB::table('communicationlog as co')
            ->select('co.*','au.name as admin_name')
            ->leftJoin('customer as c', 'co.member_id', '=', 'c.id')
            ->leftJoin('admin_users as au','co.admin_user_id','=','au.id')
            ->leftJoin('member as m', function ($join) use ($id) {
                $join->on('m.name', '=', 'c.name')
                    ->on('m.mobile', '=', 'c.mobile');
            })
            ->where('m.id','=',$id)
            ->orderBy('co.id','desc')
            ->get();
        $contact_log = json_decode(json_encode($contact_log),true);
        if (!$res && !$contact_log){
            return false;
        }
        if ($contact_log){
            foreach ($contact_log as &$v){
                $v['is_contact'] = 1;
                array_push($res,$v);
            }
        }
        $last_names = array_column($res,'created_at');
        array_multisort($last_names,SORT_DESC,$res);
        $data['data'] = $res;unset($v);
        $data['next_time'] = '';
        foreach ($data['data'] as &$v){
            if ($data['next_time'] == ''){
                $data['next_time'] = $v['comm_time'];
            }else{
                if ($data['next_time'] < $v['comm_time']){
                    $data['next_time'] = $v['comm_time'];
                }
            }
            if(!empty($v["pic"])){
                $v["pic"] = explode(",", $v["pic"]);
            }
        }
        return $data;
    }

    //添加沟通记录
    public function addContact($fields){
        $fields['created_at'] = Carbon::now()->toDateTimeString();
        $fields["mall_id"] = request()->mallData["id"];
        $res = DB::table($this->table)->insert($fields);
        if (!$res){
            return false;
        }
        return true;
    }
}
